package com.stormkai.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.stormkai.error.BusinessException;
import com.stormkai.error.EnumBusinessError;
import com.stormkai.response.CommonReturnType;
import com.stormkai.service.OrderService;
import com.stormkai.service.model.OrderModel;
import com.stormkai.service.model.UserModel;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/order")
@CrossOrigin(origins= {"*"}, allowCredentials="true")
@Slf4j
public class OrderController extends BaseController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private HttpServletRequest httpServletRequest;
	
	@PostMapping(value="/create",consumes= {"application/x-www-form-urlencoded"})
	public CommonReturnType create(@RequestParam(name="itemId") Integer itemId, @RequestParam(name="amount") Integer amount, @RequestParam(name="promoId",required=false) Integer promoId) throws BusinessException {
		
		Boolean isLogin = (Boolean)httpServletRequest.getSession().getAttribute("IS_LOGIN");
		
		if(isLogin == null || !isLogin.booleanValue()) {
			throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"用户还未登录，不能下单！");
		}
		
		//获取用户的登录信息
		UserModel userModel = (UserModel)httpServletRequest.getSession().getAttribute("LOGIN_USER");
		
		
		OrderModel orderModel = orderService.createOrder(userModel.getId(), itemId, promoId, amount);
		return CommonReturnType.create(null);
	}

}
